﻿<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="TravelManagement._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript" src="Scripts/jquery-1.7.js"></script>
    <script type="text/javascript" src="Scripts/jquery.blockUI.js"></script>
    <script type="text/javascript">

        var geocoder;
        var map;
        var markers = new Array();
        var distanceMatrix = null;
        var directionsDisplay;
        var directionsService = new google.maps.DirectionsService();
        var arrayofPositions;
        var addrArray = [];



        //On Load. Creates the maps canvas.
        window.onload = function initialize() {
            directionsDisplay = new google.maps.DirectionsRenderer();
            geocoder = new google.maps.Geocoder();
            var latlng = new google.maps.LatLng(12.971857, 77.594111);
            var myOptions = {
                zoom: 14,
                center: latlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            }
            map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
            directionsDisplay.setMap(map);

            google.maps.event.addListener(map, 'click', function (event) {

                addMarker(event.latLng);
            });

            if (document.getElementById('MainContent_ddlMyMaps') != null) {
                var savedMarkerString = document.getElementById('MainContent_ddlMyMaps').value;

                if (savedMarkerString != "") {

                    
                    var savedMarkers = JSON.parse(savedMarkerString);

                    for (var i = 0; i < savedMarkers.length; i++) {

                        var latlng = new google.maps.LatLng(savedMarkers[i].Pa, savedMarkers[i].Qa);
                        addMarker(latlng);
                    }

                }
            }

        }


        //Even handler for Add location button. 
        //Searches for the typed address, and adds a marker for the first result.
        //Recalculates the distance matrix every time a new location is added.
        function AddLocationFromTextBox() {

            var address = document.getElementById("MainContent_txtAddLocation").value;
            addrArray.push(address);
            document.getElementById("MainContent_txtAddLocation").value = "";

            geocoder.geocode({ 'address': address },
            function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {

                    var selectedPosition = results[0].geometry.location;
                    map.setCenter(results[0].geometry.location);

                    addMarker(selectedPosition);

                }
                else {
                    alert("Geocode was not successful for the following reason: " + status);
                }
            });
        }


        function addMarker(selectedPosition) {

            var markerOptions =

            {
                map: map,
                position: selectedPosition,
                draggable: true
            };

            var marker = new google.maps.Marker(markerOptions);

            google.maps.event.addListener(marker, 'dragend', function () {
                UpdateDistanceMatrix();
            });

            google.maps.event.addListener(marker, 'dblclick', function () {

                removeMarker(marker);

            });

            markers.push(marker);
            marker.setIcon("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=" + (markers.length) + "|c41200|ffffff");


            UpdateDistanceMatrix();

        }

        function removeMarker(marker) {
            var markerIcon = marker.getIcon();
            var markerIndex = markerIcon[62];
            markers.splice(markerIndex - 1, 1);
            marker.setMap(null);
            for (var i = 0; i < markers.length; i++) {
                markers[i].setIcon("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=" + (i + 1) + "|c41200|ffffff");
            }

            UpdateDistanceMatrix();
        }


        function UpdateDistanceMatrix() {

            if (markers.length < 2) {
                distanceMatrix = null;
                return;
            }


            //Only for debugging purposes.
            //var concatenatedLocationString = GetConcatenatedLocationstring();
            //alert(concatenatedLocationString);
            //var apiCallUrl = "http://maps.googleapis.com/maps/api/distancematrix/json?" + "origins=" + concatenatedLocationString + "&destinations=" + concatenatedLocationString + "&mode=driving&language=en-US&sensor=false";
            //alert(apiCallUrl);

            arrayofPositions = GetArrayOfPositions();
            var service = new google.maps.DistanceMatrixService();
            service.getDistanceMatrix(
                {
                    origins: arrayofPositions,
                    destinations: arrayofPositions,
                    travelMode: google.maps.TravelMode.DRIVING,
                    unitSystem: google.maps.UnitSystem.METRIC,
                    avoidHighways: false,
                    avoidTolls: false
                }, DistanceMatrixApiCallback);
        }


        function DistanceMatrixApiCallback(response, status) {
            // debugger;

            if (ValidateDistanceMatrixApiResponse(response)) {
                distanceMatrix = response;
            }
            else {
                alert("Invalid response from the server. May be due to bad inputs");
            }
        }

        //TODO:Code to validate response returned by Distance Matrix.
        //All elements other than the diagonal elements should be non zero.
        function ValidateDistanceMatrixApiResponse() {
            return true;
        }

        function GetArrayOfPositions() {

            var array = new Array();
            for (i = 0; i < markers.length; i++) {
                array.push(markers[i].position);
            }
            return array;
        }

        function GetConcatenatedLocationstring() {

            var concatString = "";

            for (i = 0; i < markers.length; i++) {
                concatString += markers[i].position;

                if (i != markers.length - 1) {
                    concatString += "|";
                }
            }

            return concatString;
        }

        function routeDisplay() {

            if (markers.length == 1 || markers.length == 0 || markers.length > 8)
                alert("Invalid input");
            else {
                // block UI  http://jquery.malsup.com/block/
                $.blockUI({ message: '<img src="images/GEARS_AN.GIF" />' });

                //how to call .ashx from c#.net
                //http://brijbhushan.net/2011/05/29/call-httphandler-from-jquery-pass-data-and-retrieve-in-json-format/
                $.ajax({
                    type: "POST",
                    url: "ShortestPathCalculator.ashx",

                    data: JSON.stringify(distanceMatrix),
                    processData: false,
                    success: OnComplete,
                    error: OnFail
                });
            }
        }

        function OnComplete(result) {

            $.unblockUI();
           
            var shortestPath = JSON.parse(result);
            var arrayOfPos = GetArrayOfPositions();
            var i;
            var waypts = [];
            for (i = 1; i < shortestPath.length-1; i++) {

                waypts.push({
                    location: arrayOfPos[shortestPath[i]],
                    stopover: true
                });
            }

            var request = {
                origin: arrayOfPos[shortestPath[0]],
                destination: arrayOfPos[shortestPath[shortestPath.length - 1]],
                waypoints: waypts,
                optimizeWaypoints: false,
                travelMode: google.maps.DirectionsTravelMode.DRIVING
            };

            for (var i = 0; i < markers.length; i++) {

                markers[i].setVisible(false);
            }

            directionsService.route(request, function (response, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                    debugger;
                    directionsDisplay.setDirections(response);

                    var directionsString = "<input type='button' value='Print' onclick='window.print();' />";

                    directionsString = directionsString + "<div><ol>";

                    for (var i = 0; i < response.routes[0].legs.length; i++) {
                        directionsString = directionsString + "<li><h3>" + response.routes[0].legs[i].start_address + " to " + response.routes[0].legs[i].end_address + "</h3></li><ol>";
                        for (var j = 0; j < response.routes[0].legs[i].steps.length; j++) {
                            directionsString = directionsString + "<li>" + response.routes[0].legs[i].steps[j].instructions + "</li>";
                        }
                        directionsString = directionsString + "</ol>";
                    }

                    directionsString = directionsString + "</ol></div>";

                    debugger;
                    var my_window = window.open("", "Directions", "location=0,scrollbars=1,status=0,width=500,height=500");

                    my_window.document.write(directionsString);

                }
            });


        }
        function OnFail(result) {

            $.unblockUI();
            alert("failed");

        }

        function saveToDb() {
            
            var saveName = prompt("Enter the name of the map");
            if (!saveName) {
                return false;
            }
            else {
                arrayofPositions = GetArrayOfPositions();
                document.getElementById('MainContent_hdnSaveName').value = saveName;
                document.getElementById('MainContent_hdnSaveDataField').value = JSON.stringify(arrayofPositions);
                return true;
            }
        }

    </script>
</asp:Content>
<asp:Content ID="Content1" runat="server" ContentPlaceHolderID="MainContent">
    <asp:HiddenField ID="hdnSaveDataField" runat="server" />
    <asp:HiddenField ID="hdnSaveName" runat="server" />
    <div>
        <div id="map_canvas" style="width: 100%; height: 500px">
        </div>
        <center>
            <p>
                &nbsp;<asp:TextBox ID="txtAddLocation" runat="server" Width="228px" Height="40px"
                    Font-Size="Large" />
                &nbsp;&nbsp;
                <asp:Button Text="Add a New Location" ID="btnAdd" runat="server" Width="134px" Height="40px"
                    OnClientClick="AddLocationFromTextBox(); return false;" />
                <br />
                <br />
                <asp:Label ID="lblMyMaps" runat="server" Text="My Maps"></asp:Label><br />
                <asp:DropDownList ID="ddlMyMaps" AutoPostBack="true" runat="server" 
                    Width="228px" Height="30px" AppendDataBoundItems="True">
                    
                </asp:DropDownList>
            </p>
            <asp:Label ID="Label2" Text="Calculate the round trip" runat="server" />
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <asp:Label ID="lblSaveMap" Text="Click to save the map" runat="server" />
            <br />
            <asp:Button Text="Calculate" ID="btnCalculate" runat="server" Width="100px" Height="40px"
                OnClientClick="routeDisplay(); return false;" />
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <asp:Button Text="Save" ID="btnSave"  OnClientClick="return saveToDb();" 
                runat="server" Width="100px" Height="40px" onclick="btnSave_Click"  />
        </center>
    </div>
</asp:Content>
